/**
 * Copyright (c) 2016 Lenovo Group
 * All Rights Reserved.
 * 
 * Project Name:app-gateway
 * Create Time: 2016年1月20日 下午4:31:22
 */
package com.lenovo.lmrp.server.appgateway.mock;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lenovo.lmrp.api.appgateway.IAppTicket;
import com.lenovo.lmrp.api.itsmgateway.IItsmTicket;
import com.lenovo.lmrp.api.model.RestResponse;
import com.lenovo.lmrp.api.model.entity.AttachmentPO;
import com.lenovo.lmrp.api.model.view.AttachmentUploadVO;
import com.lenovo.lmrp.api.model.view.AttachmentVO;
import com.lenovo.lmrp.api.model.view.ChangedTicketVO;
import com.lenovo.lmrp.api.model.view.SearchListFilter;
import com.lenovo.lmrp.api.model.view.TicketTotalVO;
import com.lenovo.lmrp.api.model.view.TicketVO;
import com.lenovo.lmrp.base.FTPService;
import com.lenovo.lmrp.base.FileSystemService;
import com.lenovo.lmrp.base.IFileService;
import com.lenovo.lmrp.server.appgateway.RestClientFactory;
import com.lenovo.lmrp.server.appgateway.util.PropertiesUtil;
import com.lenovo.sdc.framework.annotation.RestService;
import com.lenovo.sdc.framework.rest.RestClientProxy;
import com.lenovo.sdc.framework.util.CommonUtil;
import com.lenovo.sdc.framework.util.Tuple;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * @author zhangzhenga
 *
 */
@RestService
@Path("/app/v1")
@Consumes("application/json;charset-utf-8")
@Produces("application/json;charset-utf-8")
public class MockAppTicketImpl implements IAppTicket {
    private static final Logger logger = LoggerFactory.getLogger(MockAppTicketImpl.class);

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppTicket#getTicketList(java.lang.String, int, int, java.lang.String, int, java.lang.String, java.lang.String, java.lang.String)
     */
    public RestResponse<List<TicketVO>> getTicketList(String itsmcode, SearchListFilter condition) {
        
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
        if(!CommonUtil.isNullOrEmpty(condition.getTimeRange())){
            String[] tr = condition.getTimeRange().split("-");
            try {
                Date timeStart = format.parse(tr[0]);
                if(!CommonUtil.isNullOrEmpty(tr[1])){
                    Date timeEnd = format.parse(tr[1]);
                }
            }
            catch (ParseException e) {
                return new RestResponse<List<TicketVO>>(1, "错误的时间格式.", null);
            }
        }
        List<TicketVO> ticketVOs = new ArrayList<TicketVO>();
        for (int i = 0; i < 3; i++) {
            TicketVO vo = new TicketVO();
            vo.setTicketid(String.valueOf(i));//工单ID
            vo.setTitle("测试工单" + i);//工单标题
            vo.setProject("MS");//项目
            vo.setPriority("高");//优先级
            vo.setCaddress("西北旺东路10号院2号楼");//客户地址
            vo.setcTime(new Date());//创建时间
            vo.setPosition("40.0531760121:116.3041211900");//上门地址经纬度
            if (condition.getStatus() == 1) {//接单
                Map<String, Object> sta = new HashMap<>();
                sta.put("code", "接单时效");
                sta.put("value", new Date());
                vo.setStatus(sta);
            }
            else if (condition.getStatus() == 0) {//抢单
                
            }
            else if (condition.getStatus() == 2) {//活动工单
                Map<String, Object> sta = new HashMap<>();
                sta.put("code", "预约时效");
                sta.put("value", new Date[]{new Date(),new Date()});
                vo.setStatus(sta);
            }
            else if (condition.getStatus() == 4) {//历史工单
                vo.setAmount(103.2);//收益
            }
            
            // 倒计时
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            List<Date> timers = new ArrayList<>();
            timers.add(calendar.getTime());
            calendar.add(Calendar.SECOND, 600);
            timers.add(calendar.getTime());
            calendar.add(Calendar.SECOND, 600);
            timers.add(calendar.getTime());
            calendar.add(Calendar.SECOND, 600);
            timers.add(calendar.getTime());
            vo.setTimers(timers);

            
            ticketVOs.add(vo);
        }
        return new RestResponse<List<TicketVO>>(0, "OK", ticketVOs);
    }

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppTicket#getTicket(java.lang.String, java.lang.String)
     */
    public RestResponse<TicketVO> getTicket(String itsmcode, String ticketid) {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppTicket#updateTicket(java.lang.String, java.lang.String, java.lang.String, com.lenovo.lmrp.api.model.view.ChangedTicket)
     */
    public RestResponse<String> updateTicket(String itsmcode, String ticketid, String action, ChangedTicketVO ticket) {
        
        return new RestResponse<String>(0, "ok", null);
    }

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppTicket#uploadAttachments(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.ws.rs.container.AsyncResponse)
     */
    public RestResponse<Integer> uploadAttachments(String itsmcode, String ticketid,
                                                   AsyncResponse asyncResponse) {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppTicket#getTicketTotal(java.lang.String)
     */
    @Override
    public RestResponse<TicketTotalVO> getTicketTotal(String itsmcode) {
        TicketTotalVO total = new TicketTotalVO();
        total.setAcceptqty(10);
        total.setGrabqty(5);
        return new RestResponse<TicketTotalVO>(0, "ok", total);
    }

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppTicket#getTicketGrabResult(java.lang.String, java.lang.String)
     */
    @Override
    public RestResponse<Object> getGrabResult(String itsmcode, String ticketid) {
        logger.debug("itsmcode is {}",itsmcode);
        logger.debug("ticketid is {}",ticketid);
        return new RestResponse<Object>(0, "ok", 0);
    }

    /** 
     * @see com.lenovo.lmrp.api.appgateway.IAppTicket#createAttachment(java.lang.String, java.lang.String, com.lenovo.lmrp.api.model.view.AttachmentVO)
     */
    @Override
    public RestResponse<List<String>> createAttachment(String itsmcode, String ticketid, AttachmentUploadVO attachmentVO) {
        for (String path : attachmentVO.getOriginal()) {
            logger.debug(path);
        }
        return null;
    }
    
    /** 
     * @see com.lenovo.lmrp.api.appgateway.IAppTicket#uploadAttachment(java.lang.String, java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.ws.rs.container.AsyncResponse)
     */
    @Override
    public void uploadAttachment(String itsmcode, String ticketid, String attachmentid, HttpServletRequest request,
                                 AsyncResponse asyncResponse) {
            try {
                new TestThread(itsmcode, ticketid, attachmentid, request.getParts(), asyncResponse).start();
            }
            catch (IOException e) {
                logger.error("", e);
            }
            catch (ServletException e) {
                logger.error("", e);
            }
    }
	
	private class TestThread extends Thread {
	    Collection<Part> parts;
	    AsyncResponse asyncResponse;
	    String itsmcode, ticketid, attachmentid;
	    
	    TestThread(String itsmcode, String ticketid, String attachmentid,Collection<Part> parts, AsyncResponse asyncResponse) {
	        this.parts = parts;
	        this.asyncResponse = asyncResponse;
	        this.itsmcode = itsmcode;
	        this.attachmentid = attachmentid;
	        this.ticketid = ticketid;
	    }
	    
	    public void run() {
	        try {
                RestResponse<Integer> response=new RestResponse<Integer>(ErrorCode.COMM_ERROR.getCode(), "Unknow", -1);
                for (Part part : parts) {
                    //上传文件至ftp
                    String header = part.getHeader("content-disposition");
                    String fileName = getFileName(header);
                    if (Objects.nonNull(part.getContentType()) && header.contains("filename=\"")) {
                        String fileServerType = PropertiesUtil.getStringValue("file.server.type", "local");
                        IFileService fileService = null;
                        if(fileServerType.equalsIgnoreCase("local")){
                            fileService = new FileSystemService(PropertiesUtil.getAttributeBean());
                        }
                        else{
                            fileService = new FTPService(PropertiesUtil.getAttributeBean());
                        }
                        Tuple.Pair<String, Long> result = fileService.writeFile(itsmcode + "/" + ticketid + "/" + attachmentid + "-" + fileName, part.getInputStream());
                        part.getInputStream().close();
                    }
                }
                asyncResponse.resume(Response.ok(response).build());
            }
            catch (Exception exp) {
                TraceableException.writeLog(ErrorCode.FILE_READ_FAILED, itsmcode + ":" + attachmentid, exp);
            }
	    }
	}
    private String getFileName(String header) {
        /**
         * String[] tempArr1 =
         * header.split(";");代码执行完之后，在不同的浏览器下，tempArr1数组里面的内容稍有区别
         * 火狐或者google浏览器下：tempArr1={form-data;name="file";filename="snmp4j--api.zip"}
         * IE浏览器下：tempArr1={form-data;name="file";filename="E:\snmp4j--api.zip"}
         */
        String[] tempArr1 = header.split(";");
        /**
         * 火狐或者google浏览器下：tempArr2={filename,"snmp4j--api.zip"}
         * IE浏览器下：tempArr2={filename,"E:\snmp4j--api.zip"}
         */
        String[] tempArr2 = tempArr1[2].split("=");
        // 获取文件名，兼容各种浏览器的写法
        String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
        return fileName;
    }




}
